<template>
  <el-upload
    ref="upload"
    class="upload-demo"
    action="http://127.0.0.1:8000/user/uploadImage/"
    :limit="1"
    :on-exceed="handleExceed"
    :auto-upload="false"
    :on-success="handleSuccess"
  >
    <template #trigger>
      <el-button type="primary">身份证照片</el-button>
    </template>
    <el-button class="ml-3" type="success" @click="submitUpload">
      提交
    </el-button>
    <template #tip>
      <div class="el-upload__tip text-red">
        limit 1 file, new file will cover the old file
      </div>
    </template>
  </el-upload>
  <el-button type="primary" @click="verify">验证</el-button>
</template>

<script setup>
  import { ref, onMounted } from "vue"
  import { useRoute, useRouter } from "vue-router";
  import http from "../http"
  import axios from "axios"
  import { genFileId } from 'element-plus'

  const route = useRoute()
  const router = useRouter()

  const upload = ref(null)

  let url = ref("")

  let message = ref("")

  let token = localStorage.getItem("access_token")

  const handleExceed = (files) => {
    upload.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    upload.value.handleStart(file)
  }

  const handleSuccess = (response, file, fileList) => {
    console.log(response)
    url.value = response.url
  }

  const submitUpload = () => {
    upload.value.submit()
  }

  const verify = () => {
    http.post(`user/submitImage/`, {url: url.value})
    .then(res=>{
      console.log(res)
      getcardmes()
    })
  }

  const getcardmes = ()=>{
    const t = setInterval(()=>{
      http.post(`user/getInfo/`, {url: url.value})
      .then(res=>{
        console.log(res)
        if(res.data.code == 200){
          message.value = res.data.message
          clearInterval(t)
          createUser()
        }
      })
    },1000)
  }

  // 创建实名用户
  const createUser = () => {
    axios.post(`http://127.0.0.1:8000/user/userAuth/`, {url: url.value, message: message.value}, {
    headers: {
      Authorization: "Bearer " + token
    }})
    .then(res=>{
      console.log(res)
    })
    .catch(err=>{
      console.log(err)
    })
  }

</script>
